﻿Imports System.IO
Imports System.Net
Imports System.Text

Namespace TweeVo
	Public NotInheritable Class Twitter
		Private Sub New()
		End Sub
		Public Shared Function VerifyTwitterCredentials(ByVal username As String, ByVal password As String) As Boolean
			' call the "verify_credentials" api with the supplied credentials and see if we succeed
			Dim request As HttpWebRequest = CType(WebRequest.Create("http://twitter.com/account/verify_credentials.xml"), HttpWebRequest)

			request.Method = "GET"
			request.Credentials = New NetworkCredential(username, password)
			request.ServicePoint.Expect100Continue = False

			Dim resp As HttpWebResponse = Nothing

			Try
				resp = CType(request.GetResponse(), HttpWebResponse)
			Catch e1 As WebException
				Return False
			Finally
				If resp IsNot Nothing Then
					resp.Close()
				End If
			End Try

			Return True
		End Function

		Public Shared Sub PostTwitterUpdate(ByVal tweet As String)
			Logger.Log("Tweet: " & tweet, LoggerSeverity.Info)

			' turn the tweet into a byte array
			Dim bytes() As Byte = Encoding.ASCII.GetBytes("source=tweevo&status=" & tweet)

			Dim request As HttpWebRequest = CType(WebRequest.Create("http://twitter.com/statuses/update.xml"), HttpWebRequest)

			' post that byte array up to the server
			request.Method = "POST"
			request.Credentials = New NetworkCredential(TweeVoSettings.Default.TwitterUsername.DecryptString(), TweeVoSettings.Default.TwitterPassword.DecryptString())
			request.ServicePoint.Expect100Continue = False
			request.ContentType = "application/x-www-form-urlencoded"

			request.ContentLength = bytes.Length

			Dim reqStream As Stream = request.GetRequestStream()

			reqStream.Write(bytes, 0, bytes.Length)

			reqStream.Close()

			Dim resp As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
			resp.Close()
		End Sub
	End Class
End Namespace
